package com.xiaochaohao.wiki.service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.xiaochaohao.wiki.domain.Category;
import com.xiaochaohao.wiki.domain.CategoryExample;
import com.xiaochaohao.wiki.domain.Doc;
import com.xiaochaohao.wiki.domain.DocExample;
import com.xiaochaohao.wiki.mapper.DocMapper;
import com.xiaochaohao.wiki.req.CategoryQueryReq;
import com.xiaochaohao.wiki.req.CategorySaveReq;
import com.xiaochaohao.wiki.req.DocQueryReq;
import com.xiaochaohao.wiki.resp.CategoryQueryResp;
import com.xiaochaohao.wiki.resp.DocQueryResp;
import com.xiaochaohao.wiki.resp.PageResp;
import com.xiaochaohao.wiki.util.CopyUtil;
import com.xiaochaohao.wiki.util.SnowFlake;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.List;

@Service
public class DocService {
    @Resource
    private DocMapper docMapper;
    @Resource
    private SnowFlake snowFlake;
    public PageResp<DocQueryResp> list(DocQueryReq req) {
        DocExample categoryExample = new DocExample();
        categoryExample.setOrderByClause("sort desc");
        DocExample.Criteria criteria = categoryExample.createCriteria();
        PageHelper.startPage(req.getPage(),req.getSize());
        List<Doc> categoryList = docMapper.selectByExample(categoryExample);
        PageInfo<Doc> pageInfo = new PageInfo<>(categoryList);
        List<DocQueryResp> list = CopyUtil.copyList(categoryList,DocQueryResp.class);
        PageResp<DocQueryResp> pageResp = new PageResp<>();
        pageResp.setList(list);
        pageResp.setTotal(pageInfo.getTotal());
        return pageResp;
    }

    public void save(CategorySaveReq req) {
        Doc category = CopyUtil.copy(req,Doc.class);
        if (ObjectUtils.isEmpty(category.getId())){
            category.setId(snowFlake.nextId());
            docMapper.insert(category);
        }else {
            docMapper.updateByPrimaryKey(category);
        }
    }

    public void delete(Long id) {
        docMapper.deleteByPrimaryKey(id);
    }

    public List<DocQueryResp> all() {
        DocExample categoryExample = new DocExample();
        categoryExample.setOrderByClause("sort asc");
        List<Doc> categoryList = docMapper.selectByExample(categoryExample);
        List<DocQueryResp> list = CopyUtil.copyList(categoryList,DocQueryResp.class);
        return list;
    }
}
